package com.william.taskrobot.service.faq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.william.taskrobot.mapper.FaqMapper;
import com.william.taskrobot.model.entity.Faq;
import com.william.taskrobot.service.NlpService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.List;
import java.util.Map;

/**
 * SimpleQuery class
 * 简单查询，通过数据库计算相似度进行查询
 * @author william
 * @date 2021/1/19
 */
@Service
public class SimpleQuery {
    @Autowired
    private FaqMapper faqMapper;
    public String query(String question) {
        QueryWrapper<Faq> queryWrapper=new QueryWrapper<>();
        List<Faq> faqList=faqMapper.selectList(queryWrapper);
        Map<Integer,Float> scoreMap= Maps.newHashMap();
        faqList.forEach(faq -> {
            float score= NlpService.getSimaly(question,faq.getQuestion());
            scoreMap.put(faq.getId(),score);
        });
        List<Map.Entry<Integer, Float>> entryList = new ArrayList<Map.Entry<Integer, Float>>(
                scoreMap.entrySet());
        Collections.sort(entryList, new Comparator<Map.Entry<Integer, Float>>() {
            @Override
            public int compare(Map.Entry<Integer, Float> o1, Map.Entry<Integer, Float> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        if(entryList.get(0).getValue().compareTo(0.7f)>0){
            return faqMapper.selectById(entryList.get(0).getKey()).getAnswer();
        }
        else
        {
            return StringUtils.EMPTY;
        }

    }
}
